# -*- encoding: utf-8 -*-
"""
File Name: load_cmdb_info
Description:
Author : 'lirui'
date: 2024/6/4
Contact: marjey_lee@163.com
Change Activity:
2024/6/4:
"""
import ll
from ll.utils.network.ip_re import is_ipv4
from modules.blk.cmdb.common.cmdb_api import CMDBAPI


def _format_ip(ip_str):
    try:
        if len(ip_str) < 3:
            return None, None
        ip1, ip2 = ip_str.split('/')
        i = ip1.split('.')
        assert len(i) == 4
        ip2 = f'{i[0]}.{i[1]}.{i[2]}.{ip2}'
        assert is_ipv4(ip1)
        assert is_ipv4(ip2)
        return ip1, ip2
    except Exception as e:
        print(ip_str)
        ll.get_logger().error(f"format ip string error: {ip_str},{e}")
        return None, None


def load_branch_dedicated_info_from_cmdb():
    """

    Returns:

    """
    api = CMDBAPI()
    res = api.select_all('fd_network_ip_address')
    data = res['data']['info']
    data_mapping = {}
    for item in data:
        for ip_str in [item['unicom_ip'], item['telec_line_nub']]:
            if is_ipv4(ip_str):
                data_mapping[ip_str] = item['bk_inst_name']
                continue
            ip1, ip2 = _format_ip(ip_str)
            if ip1 is None or ip2 is None:
                continue
            for ip_ in [ip1, ip2]:
                data_mapping[ip_] = item['bk_inst_name']
    return data_mapping


def _main():
    data = load_branch_dedicated_info_from_cmdb()
    print(data)


if __name__ == '__main__':
    _main()
